<template>
    <div class="app-container">
        <div style="margin-bottom: 10px;">
            <el-button type="primary" style="margin-bottom: 15px;margin-top: 10px;"
                @click="ShowUpload">上传分析文件</el-button>
            <el-select v-model="selectedFile" placeholder="分析文件前请先上传文件">
                <el-option v-for="file in fileList" @click="handleFileChange(file)" :key="file.fileId"
                    :label="file.fileName" :value="file.fileId">
                </el-option>
            </el-select>
        </div>
        <el-dialog title="文件操作" v-model="dialogVisible">
            <span>您选择了文件: {{ fileNames }}</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleAnalyze(fileIds)">分 析</el-button>
                <el-button type="danger" @click="handleDeleteFile">删 除</el-button>
            </span>
        </el-dialog>
        <el-dialog title="文件操作" v-model="dialogShow">
            <span>文件正在分析，请等候... {{ seconds }}</span>
        </el-dialog>
        <el-dialog title="上传文件" v-model="uploadShow">
            <span>选中文件之后即可自动上传</span>
            <upload-file-vue></upload-file-vue>
        </el-dialog>

        <el-table :data="tableList" @selection-change="handleSelectionChange" max-height="700px">
            <el-table-column type="selection" align="center" width="55"></el-table-column>
            <el-table-column label="序号" type="index" width="50" align="center">
                <template #default="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="学号" align="center" prop="id" />
            <el-table-column label="姓名" align="center" prop="name" />
            <el-table-column label="专业" align="center" prop="department" />
            <el-table-column label="创建时间" align="center" prop="createtime" width="160" />
            <!-- <el-table-column label="预警等级" align="center" prop="alertLevel" width="160" /> -->
            <el-table-column label="预警等级" align="center" width="160">
                <template #default="scope">
                    <el-tag :type="getAlertLevelType(scope.row.alertLevel)">
                        {{ scope.row.alertLevel }}
                    </el-tag>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup name="Gen">
    /* -------------------------------*/
    import {
        getFetchFileWarn,
        listTable,
        previewTable,
        delTable,
        genCode,
        synchDb,
        getFetchFileList,
        deleteFetchFileList
    } from "@/api/tool/gen";
    import router from "@/router";
    import importTable from "./importTable";
    import createTable from "./createTable";
    import {
        ref,
        onMounted,
        onUnmounted
    } from 'vue';
    import {
        get
    } from "@vueuse/core";
    import axios from "axios";
    import uploadFileVue from "../../../components/aaaIndex/uploadFile.vue";
    import {
        ElMessage
    } from "element-plus";
    const fileList = ref([]); // 文件列表
    const selectedFile = ref(''); // 当前选中的文件
    const dialogVisible = ref(false); // 对话框是否可
    const dialogShow = ref(false); // 对话框是否可
    const uploadShow = ref(false)
    const ShowUpload = () => {
        uploadShow.value = true
    };
    const getAlertLevelType = (alertLevel) => {
        switch (alertLevel) {
            case '一级预警':
                return 'primary'; // 蓝色标签
            case '二级预警':
                return 'warning'; // 黄色标签
            case '三级预警':
                return 'danger'; // 红色标签
            default:
                return 'success'; // 默认情况，不设置标签颜色
        }
    };
    // 获取文件列表
    const fetchFileList = async () => {
        try {
            const response = await getFetchFileList();
            console.log('接口调用成功：', response);
            fileList.value = response.data;
            console.log('文件列表：', fileList.value);
        } catch (error) {
            console.error('获取文件列表失败:', error);
        }
    };
    onMounted(() => {
        fetchFileList();
        if (dialogShow.value) {
            startTimer();
        }
    });
    onUnmounted(() => {
        stopTimer();
    });
    fetchFileList()
    // 处理文件选择变化
    const fileNames = ref();
    const fileIds = ref();
    const handleFileChange = (file) => {

        selectedFile.value = file;
        fileIds.value = selectedFile.value.fileId;
        fileNames.value = selectedFile.value.fileName;
        console.log(fileNames.value)
        console.log(fileIds.value)

        dialogVisible.value = true;
    };


    // 分析文件
    const handleAnalyze = async (id) => {
        console.log("id:", id)
        try {
            dialogVisible.value = false;
            dialogShow.value = true;
            const response = await getFetchFileWarn(id)
            tableList.value = response.data.map(item => {
                if (!item.createtime) {
                    let date = new Date(); // 创建一个Date对象，默认是本地时间
                    item.createtime = date.toLocaleString('zh-CN', {
                        hour12: false
                    }).replace(',', ' ');
                }

                if (item.id) {
                    if (item.id.length <= 5) {
                        item.id = item.id;
                    } else {
                        item.id = item.id.slice(0, 3) + '*'.repeat(item.id.length -
                            6) + item.id.slice(-3);
                    }
                }

                if (item.name) {
                    if (item.name.length === 2) {
                        item.name = item.name[0] + '*';
                    } else if (item.name.length === 3) {
                        item.name = item.name[0] + '*' + item.name.slice(-1);
                    } else {
                        // 其他情况，第一个字以后到最后一个字之间的都设置为*
                        item.name = item.name[0] + '*'.repeat(item.name.length - 2) + item.name.slice(-
                            1);
                    }
                }
                return item;
            });
            if (response) {
                dialogShow.value = false;
            }
            console.log(response)
            console.log(tableList.value)
            console.log('分析成功');
        } catch (error) {
            dialogShow.value = false;
            console.error('分析失败:', error);
        } finally {
            dialogShow.value = false;
            dialogVisible.value = false;
        }
    };

    // 删除文件
    const handleDeleteFile = async (id) => {
        try {
            await deleteFetchFileList(id);
            console.log('删除成功');
            await fetchFileList(); // 刷新文件列表
        } catch (error) {
            console.error('删除失败:', error);
        } finally {
            dialogVisible.value = false;
        }
    };


    const timerId = ref(null);
    const seconds = ref(0);

    function startTimer() {
        timerId.value = setInterval(() => {
            seconds.value++;
        }, 1000);
    }

    function stopTimer() {
        if (timerId.value) {
            clearInterval(timerId.value);
            timerId.value = null;
        }
    }
    watch(dialogShow, (newValue) => {
        if (newValue) {
            startTimer();
        } else {
            stopTimer();
            seconds.value = 0; // 重置秒数
        }
    });

    /* -------------分割线------------------*/


    const route = useRoute();
    const {
        proxy
    } = getCurrentInstance();

    const tableList = ref([]);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const tableNames = ref([]);
    const dateRange = ref([]);
    const uniqueId = ref("");

    const data = reactive({
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            tableName: undefined,
            tableComment: undefined
        },
        preview: {
            open: false,
            title: "代码预览",
            data: {},
            activeName: "domain.java"
        }
    });

    const {
        queryParams,
        preview
    } = toRefs(data);

    onActivated(() => {
        const time = route.query.t;
        if (time != null && time != uniqueId.value) {
            uniqueId.value = time;
            queryParams.value.pageNum = Number(route.query.pageNum);
            dateRange.value = [];
            proxy.resetForm("queryForm");
            getList();
        }
    })


    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }


    /** 同步数据库操作 */
    function handleSynchDb(row) {
        const tableName = row.tableName;
        proxy.$modal.confirm('确认要强制同步"' + tableName + '"表结构吗？').then(function() {
            return synchDb(tableName);
        }).then(() => {
            proxy.$modal.msgSuccess("同步成功");
        }).catch(() => {});
    }

    /** 打开导入表弹窗 */
    function openImportTable() {
        proxy.$refs["importRef"].show();
    }

    /** 打开创建表弹窗 */
    function openCreateTable() {
        proxy.$refs["createRef"].show();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        dateRange.value = [];
        proxy.resetForm("queryRef");
        handleQuery();
    }

    /** 预览按钮 */
    function handlePreview(row) {
        previewTable(row.tableId).then(response => {
            preview.value.data = response.data;
            preview.value.open = true;
            preview.value.activeName = "domain.java";
        });
    }

    /** 复制代码成功 */
    function copyTextSuccess() {
        proxy.$modal.msgSuccess("复制成功");
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.tableId);
        tableNames.value = selection.map(item => item.tableName);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 修改按钮操作 */
    function handleEditTable(row) {
        const tableId = row.tableId || ids.value[0];
        router.push({
            path: "/tool/gen-edit/index/" + tableId,
            query: {
                pageNum: queryParams.value.pageNum
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const tableIds = row.tableId || ids.value;
        proxy.$modal.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(function() {
            return delTable(tableIds);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    }
</script>